package org.csu.mypetstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.csu.mypetstore.common.CommonResponse;
import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.dto.CartDTO;
import org.csu.mypetstore.mapper.*;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.util.SaltMD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.catalog.CatalogManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private SignOnMapper signOnMapper;
    @Autowired
    private ProfileMapper profileMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CategoryMapper categoryMapper;



    private String successMessage;
    private String errorMessage;
    public String getErrorMessage(){
        return this.errorMessage;
    }

    // 取得用户购物车信息
    public CommonResponse<List<Cart>> getMyCartByUserid(String userid) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        QueryWrapper<Account> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id", userid);
        Account account = accountMapper.selectOne(queryWrapper1);
        queryWrapper.eq("user", account.getUserId());
        List<Cart> cartList = cartMapper.selectList(queryWrapper);
        for (int i = 0; i < cartList.size(); i++) {
            Cart cart = cartList.get(i);
            QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
            itemQueryWrapper.eq("itemid", cart.getItemId());
            Item item = itemMapper.selectOne(itemQueryWrapper);
            cart.setItem(item);

            QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
            productQueryWrapper.eq("productid", item.getProductId());
            Product product = productMapper.selectOne(productQueryWrapper);
            cart.setProduct(product);

            QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
            categoryQueryWrapper.eq("catid", product.getCategory());
            Category category =  categoryMapper.selectOne(categoryQueryWrapper);
            cart.setCategory(category);

        }
        successMessage = "";
        if(cartList.size() == 0) successMessage = "您的购物车为空";
        return CommonResponse.createForSuccess(this.successMessage, cartList);
    }

    // 根据用户是否为Null判断是否登录
    public CommonResponse<Object> login(SignOn user){
        QueryWrapper<SignOn> queryWrapper=new QueryWrapper<>();
//        queryWrapper.eq("username", user.getUsername()).eq("password", user.getPassword());
        queryWrapper.eq("username", user.getUsername());
        SignOn signOn=signOnMapper.selectOne(queryWrapper);
//        if(signOn == null){
        if(!SaltMD5Util.verifySaltPassword(user.getPassword(), signOn.getPassword())){
            this.errorMessage = "用户名或密码错误";
            return CommonResponse.createForError(this.errorMessage);
        }
        this.successMessage = "";
        return CommonResponse.createForSuccess(this.successMessage, signOn);
    }

    // 根据用户名查找账号account
    public CommonResponse<Object> getAccountBySignOn(SignOn user){
        Account account = accountMapper.selectById(user.getId());
        return CommonResponse.createForSuccess(account);
    }

    public String createAccountId(){
        Random random = new Random();
        String accountId = "";
        for(int i = 0; i < 9; i ++){
            int num = random.nextInt(9);
            String numInString = String.valueOf(num);
            accountId += numInString;
        }
        return accountId;
    }

    public CommonResponse<Object> register(String username, String password){
        String base_info = "NULL";
        Account account = new Account();
        SignOn signOn = new SignOn();

        account.setUserId(username);
        account.setEmail(base_info);
        account.setFirstName(base_info);
        account.setLastName(base_info);
        account.setCountry(base_info);
        account.setCity(base_info);
        account.setZip(base_info);
        account.setState(base_info);
        account.setStatus("OK");
        account.setPhone(base_info);
        account.setAddress1(base_info);
        account.setAddress2(base_info);

        signOn.setUsername(username);
        signOn.setPassword(password);
        String accountId;
        boolean flag = false;
        QueryWrapper<SignOn> queryWrapper = new QueryWrapper<>();
        while(!flag){
            // 生成id不能和数据库中已有id重复
            accountId = createAccountId();
            System.out.println(accountId);
            queryWrapper.eq("id", accountId);
            SignOn sign = signOnMapper.selectOne(queryWrapper);
            if(sign == null){
                flag = true;
                signOn.setId(accountId);
                account.setAccountId(accountId);
            }
        }
        int result1 = signOnMapper.insert(signOn);
        int result2 = accountMapper.insert(account);
        if(result1 == 0){
            return CommonResponse.createForError("插入signOn操作失败");
        }
        if(result2 == 0){
            return CommonResponse.createForError("插入account操做失败");
        }
        return CommonResponse.createForSuccess("插入操作成功");
    }

    public CommonResponse<Object> improveInfo(Account account){
        UpdateWrapper<Account> accountUpdateWrapper = new UpdateWrapper<>();
        UpdateWrapper<SignOn> signOnUpdateWrapper = new UpdateWrapper<>();
        accountUpdateWrapper.eq("id", account.getAccountId());
        signOnUpdateWrapper.eq("id", account.getAccountId());
        SignOn signOn = signOnMapper.selectOne(signOnUpdateWrapper);
        signOn.setUsername(account.getUserId());
        int result1 = accountMapper.update(account, accountUpdateWrapper);
        int result2 = signOnMapper.update(signOn, signOnUpdateWrapper);
        if(result1 == 0 || result2 == 0){
            return CommonResponse.createForError("用户修改信息操作失败");
        }
        return CommonResponse.createForSuccess("用户修改信息成功", account);
    }

    public CommonResponse<Object> changePassword(String id, String old_password, String new_password){
        UpdateWrapper<SignOn> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).eq("password", old_password);
        SignOn signOn = signOnMapper.selectOne(updateWrapper);
        if(signOn == null){
            return CommonResponse.createForError("原密码输入错误");
        }
        signOn.setPassword(new_password);
        int result = signOnMapper.update(signOn, updateWrapper);
        if(result == 0){
            return CommonResponse.createForError("密码修改失败");
        }
        return CommonResponse.createForSuccess("用户修改密码成功", signOn);
    }



}
